package servlet.user;

import dao.UserDao;
import dao.service.UserDaoImp;
import modle.User;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @author cloudJiang
 * @date 2021/11/9 10:19
 */
@WebServlet("/userEnroll")
public class UserEnroll extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        //设置字符集
        request.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=utf-8");

        String userID = request.getParameter("userID");
        String userName = request.getParameter("userName");
        String userPassword = request.getParameter("userPassword");
        String userSex = request.getParameter("userSex");
        String userBirthday = request.getParameter("userBirthday");
        String userEmail = request.getParameter("userEmail");
        String userPhone = request.getParameter("userPhone");
        String userAddress = request.getParameter("userAddress");
        int userStatus = 1;

        //创建用户实体并且加入到数据库
        User user = new User(userID, userName, userPassword, userSex, userBirthday, null, userEmail, userPhone, userAddress, userStatus);
        UserDao userDao = new UserDaoImp();
        int count = userDao.insert(user);


        //成功或失败从定向
        if (count > 0) {
            System.out.println("注册成功，共有" + count + "行受影响");

            //插入成功则定向到User文件
            response.sendRedirect("login.jsp");
        } else {
            //获取返回流
            PrintWriter out = response.getWriter();

            out.write("<script>");
            out.write("alert('用户添加失败')");
            out.write("location.href='reg.jsp'");
            out.write("</script>");

            out.close();
        }
    }
}

